package com.yupi.springbootinit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.manager.BigModelPicture;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.mapper.PictureMapper;
import com.yupi.springbootinit.model.dto.chart.GetPictureByAiRequest;
import com.yupi.springbootinit.model.entity.Picture;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.vo.PictureVO;
import com.yupi.springbootinit.service.PictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import static com.yupi.springbootinit.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 尔特岛
* @description 针对表【picture(图片结论表)】的数据库操作Service实现
* @createDate 2025-03-13 20:41:09
*/
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    @Value("${pikimbi.picturePath}")
    private String picturePath;

    @Autowired
    private RedisLimiterManager redisLimiterManager;


    @Override
    public PictureVO getPictureMessage(GetPictureByAiRequest getPictureByAiRequest, HttpServletRequest request) {
        String goal = getPictureByAiRequest.getGoal();
        String fileName = getPictureByAiRequest.getFileName();
        if (StrUtil.isBlank(goal) || StrUtil.isBlank(fileName)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = (User)request.getSession().getAttribute(USER_LOGIN_STATE);
        String userId = user.getId().toString();

        //接口限流
        redisLimiterManager.doRateLimit("getPictureByAi_"+userId);

        try {
            //调用ai服务
            String imagePath = picturePath+fileName;
            BigModelPicture analyzer = new BigModelPicture(userId,imagePath);

            String pictureMessage = analyzer.generateAnswer(goal);

            if(StrUtil.isBlank(pictureMessage)){
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
            //写入数据库
            Picture picture = new Picture();
            picture.setGoal(goal);
            picture.setFileName(fileName);
            picture.setGenResult(pictureMessage);
            picture.setUserId(Long.parseLong(userId));
            boolean save = this.save(picture);
            if(!save){
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }

            //封装，返回
            PictureVO pictureVO = new PictureVO();
            pictureVO.setPictureMessage(pictureMessage);
            return pictureVO;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




